import { onMounted, ref } from "vue";
import { all } from "@/api/classify";
import { handleTree } from "@/utils/tree";

export function classifyFormat(type: string) {
  const classifyMenuOptions = ref([]);
  const data = ref([]);
  onMounted(async () => {
    const res = await all({ type: type });

    data.value = res.data.list;
    data.value = handleTree(data.value, "id", "parent_id"); // 处理成树结构
    classifyMenuOptions.value = formatHigherMenuOptions(data.value);
  });

  return { classifyMenuOptions };
}

function formatHigherMenuOptions(treeList) {
  if (!treeList || !treeList.length) return;
  const newTreeList = [];
  for (let i = 0; i < treeList.length; i++) {
    treeList[i].title = treeList[i].title;
    formatHigherMenuOptions(treeList[i].children);
    newTreeList.push(treeList[i]);
  }
  return newTreeList;
}
